package com.fengmi.gw.filter;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fengmi.comm.ResultVO;
import com.fengmi.sso.SysUser;
import com.fengmi.utils.bean.JwtUtils;
import com.fengmi.utils.bean.RsaUtils;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.security.PublicKey;

/**
 * 校验token的合法性
 */
@Component
public class AuthFilter  implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 登录需要放行，cms     login   search  portal
        String [] whilte = {"login","cms","search","portal"};  //login/login
        String path1 = request.getURI().getPath();  //获取请求路径
        for(String  s:whilte ){
            if(path1.contains(s)){
                return chain.filter(exchange);
            }
        }
        //获取token串
        String token = request.getHeaders().getFirst("token");
        //校验token的合法性
        String path = null;
        try {
            path = ResourceUtils.getFile("classpath:rsa_pub").getPath();
            PublicKey publicKey = RsaUtils.getPublicKey(path);
            //校验
            SysUser sysUser = (com.fengmi.sso.SysUser) JwtUtils.getInfoFromToken(token, publicKey, SysUser.class);
            String user = JSONUtil.toJsonStr(sysUser);
            ServerHttpRequest requestnew = request.mutate().header("user", user).build();
            ServerWebExchange exchangenew = exchange.mutate().request(requestnew).build();
            return chain.filter(exchangenew);
        } catch (ExpiredJwtException e) {
            e.printStackTrace();
            response(response,new ResultVO("1001","令牌超时",null));
        }catch (MalformedJwtException e) {
            response(response,new ResultVO("1001","非法令牌",null));
            e.printStackTrace();
        }
        catch (Exception e) {
            response(response,new ResultVO("1001","校验不通过",null));
            e.printStackTrace();
        }
        return  response(response,new ResultVO("1001","校验不通过",null));
    }



    private Mono<Void> response(ServerHttpResponse response, ResultVO res){
        //不能放行，直接返回，返回json信息
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");

        ObjectMapper objectMapper = new ObjectMapper();
        String jsonStr = null;
        try {
            jsonStr = objectMapper.writeValueAsString(res);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        DataBuffer dataBuffer = response.bufferFactory().wrap(jsonStr.getBytes());
        return response.writeWith(Flux.just(dataBuffer));//响应json数据
    }


    @Override
    public int getOrder() {
        return 0;
    }
}
